package io.jft.doll

import android.app.Application
import com.g.base.BaseInit
import com.g.base.token.TokenManage
import com.tencent.bugly.Bugly
import com.tencent.bugly.beta.Beta
import io.jft.doll.room.database.AppDatabase
import io.jft.doll.room.repository.CartRepository
import io.jft.doll.room.repository.MessageRepository
import io.jft.doll.room.repository.RoomRepository
import io.jft.doll.room.repository.UserRepository
import io.jft.doll.tcp.TcpHelp
import io.jft.doll.tcp.tcpClient
import org.greenrobot.eventbus.EventBus

/**
 * Created by G on 2017/11/6 0006.
 */
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        BaseInit.onCreate(this)
        initTokenManage()
        buglyInit()
        EventBus.builder().addIndex(MyEventBusIndex()).installDefaultEventBus()
        TcpHelp.init()
        RoomRepository.nukeRoomTable()
    }

    //退出登录的时候清空数据库表
    //没有创建AppDataBase时顺带创建一下数据库
    private fun initTokenManage() {
        TokenManage.getTokenLive().observeForever {
            if (it == null) {
                UserRepository.currentRemain.postValue(null)
                UserRepository.duibaAddress.postValue(null)
                UserRepository.inviteInfo.postValue(null)
                CartRepository.cartData.postValue(null)
                MessageRepository.messageData.forEach {
                    it.value.postValue(null)
                }
                AppDatabase.instant.clearAllTables()
                tcpClient.disConnect()
            } else {
                AppDatabase.instant
                tcpClient.connect()
            }
        }
    }

    private fun buglyInit() {
        Beta.initDelay = 5 * 1000L
        Beta.enableHotfix = false
        Bugly.init(this, "62eb78f57e", false)
    }
}
